- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathStack.py
33 lines (27 loc) · 820 Bytes
/
Stack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
classSolution:
defaddTwoNumbers(self, l1: ListNode, l2: ListNode) ->ListNode:
stack1= []
stack2= []
whilel1:
stack1.append(l1.val)
l1=l1.next
whilel2:
stack2.append(l2.val)
l2=l2.next
head=None
carry=0
whilestack1orstack2orcarry:
digit=carry
digit+=stack1.pop() ifstack1else0
digit+=stack2.pop() ifstack2else0
carry=1ifdigit>9else0
digit-=10ifdigit>9else0
temp=ListNode(digit)
temp.next=head
head=temp
returnhead